package network.tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpFileClient {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream stream = null;
        InputStream in = null;
        FileInputStream fileStream = null;
        ByteArrayOutputStream byteOS = null;

        try {
            //1.客户端获取服务器地址
            InetAddress serverIP = InetAddress.getByName("localhost");
            int port = 10001;

            //2.创建一个Socket连接
            socket = new Socket(serverIP, port);

            //3.发消息 IO流 文件流
            File file = new File("F:\\ProgramData\\JavaReview\\src\\network\\tcp\\res\\Aliga.jpg");
            stream = socket.getOutputStream();
            in = socket.getInputStream();
            fileStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fileStream.read(buffer))!=-1) {
                stream.write(buffer,0,len);
            }

            socket.shutdownOutput();
            //强化，确认服务器接收完毕
            byteOS = new ByteArrayOutputStream();
            byte[] buffer2 = new byte[1024];
            int len2 = 0;
            while ((len2 = in.read(buffer2))!=-1) {
                byteOS.write(buffer2,0,len2);
            }
            System.out.println(byteOS.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if (byteOS!=null) {
                try {
                    byteOS.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileStream!=null) {
                try {
                    fileStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in!=null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (stream!=null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
